package com.hsylient.redis.controller;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson2.JSON;
import com.hsylient.common.entity.User;
import com.hsylient.common.response.BaseResponse;
import com.hsylient.common.response.UserResponse;
import com.hsylient.redis.init.BloomFilterInit;
import com.hsylient.redis.service.UserService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;

@Slf4j
@RestController
public class UserController {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    private static final String USER_REDIS = "platform:user:info:";
    @Resource
    private UserService userService;

    @GetMapping("/v3/user/info")
    public BaseResponse<UserResponse> findUserInfoById(@RequestParam("userId") Long userId) {
        if (!BloomFilterInit.bloomFilter.contains(Objects.toString(userId))) {
            log.info("[用户信息查询] 未查到任何用户信息，用户Id:{}", userId);
            return BaseResponse.success();
        }
        Object jsonObject = redisTemplate.opsForValue().get(USER_REDIS + userId);
        if (Objects.isNull(jsonObject)) {
            User userFormDb = userService.findByUserId(userId);
            if (Objects.nonNull(userFormDb)) {
                redisTemplate.opsForValue().set(USER_REDIS + userId, JSON.toJSONString(userFormDb));
                BloomFilterInit.bloomFilter.add(Objects.toString(userFormDb.getId()));
                return BaseResponse.success(BeanUtil.copyProperties(userFormDb, UserResponse.class));
            } else {
                log.info("[用户信息查询] 未查到任何用户信息，用户Id:{}", userId);
                return BaseResponse.success();
            }
        } else {
            User user = JSON.parseObject(jsonObject.toString(), User.class);
            return BaseResponse.success(BeanUtil.copyProperties(user, UserResponse.class));
        }
    }
}
